/**
 * Created by PR on 2015/12/29.
 */
/* center modal */
function centerModals(){
    $('.modal').each(function(i){
        var $clone = $(this).clone().css('display', 'block').appendTo('body');    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2) - 30;
        top = top > 0 ? top : 0;
        $clone.remove();
        $(this).find('.modal-content').css("margin-top", top);
    });
}
$('.modal').on('show.bs.modal', centerModals);
$(window).on('resize', centerModals);
/* ajax */
function ajaxJsonp(url, arg ,sendSuc, method, tips, sendEro) {
    var method = method || "get";
    var sendSuc = sendSuc || null;
    var sendEro = sendEro || null;
    var loginTips = loginTips || null;
    var finalUrl = 'http://coupon.dotfive.cn';
    finalUrl = finalUrl + url;
    var token = getCookie("token");
    var city = getCookie("city");
    arg.token = token;
    arg.city_name = city;
    $.ajax({
        url: finalUrl,
        type : method,
        dataType:'jsonp',
        data: arg,
        jsonp:'callback',
        success:function(result) {
            var status = result.status;
            var code = status.code;
            if(code == 1) {
                if(sendSuc) {
                    sendSuc(result);
                }
            }
            if(code == 0) {
                if(tips) {
                    tips(result);
                } else {
                    msg = status.msg;
                    showModal(msg);
                }
        }
            if(code == 2) {
                if(tips) {
                    tips(result);
                } else {
                    msg = status.msg;
                    showModal(msg);
                }
            }
            if(code == 3) {
                if(tips) {
                    tips(result);
                } else {
                    msg = status.msg;
                    showModal(msg);
                }
            }
            if(code == 4) {
                if(tips) {
                    tips(result);
                }
            }
        },
        error:function(error) {
            console.log(error);
        /*    if(!sendEro) {
                console.log(1);
                var responseText = JSON.parse(error.responseText);
                console.log(responseText.status.msg);
                msg = responseText.status.msg
                showModal(msg);
            } else {
                sendEro(error);
            }*/
        }
    });
}
/* 显示modal*/
function showModal(msg,status) {
    var isStatus = status || false;
    $('.modal-body').text(msg);
    $(".modal-footer").html("");
    $('#myModal').modal();
    if(!isStatus) {
        setTimeout(function(){
            $('#myModal').modal("hide");
        },1000);
    }
}
/* 回调时，页面跳转 start */
function delayJump(url) {
    location.href = url;
}
function doJump(url) {
    setTimeout(function() {
        delayJump(url);
    },1000);
}
/* -------获取url中参数----- */
function getArg(arg) {
    var url = location.href;
    var args = url.split("?")[1];
    if(args) {
        var argsArray = args.split("&");
    }
    var result = {};
    for(p in argsArray) {
        var a = argsArray[p].split("=");
        result[a[0]] = a[1];
    }
    return result[arg];
}
/* ------cookie部分------ */
/* 设置cookie */
function saveCookie(name, value, time, path){
    var time = time || null;
    var path = path || null;
    if(name == "city") {
        value = encodeURIComponent(value);
    }
    var d= new Date();
    d.setHours(d.getHours() + time); //保存时间
    document.cookie = name + "=" + value + "; " + path + "; expires=" + d.toGMTString();
}
/* 获取cookie */
function getCookie(name) {
    var list = document.cookie.split("; ");
    for(var i = 0; i < list.length; i++) {
        if(list[i].split("=")[0] == name) {
            if(name == "city") {
                return decodeURIComponent(list[i].split("=")[1]);
            } else {
                return list[i].split("=")[1];
            }
        }
    }
}
/* 删除cookie */
function deleteCookie(arg) {
    var value = getCookie(arg);
    var date=new Date();
    date.setTime(date.getTime()-10000);
    document.cookie = arg + "=" + value + "; path=/; "+ "expire=" + date.toGMTString();
}
/* 图像裁剪 */


/* 判断是否登陆 */
 function isLogin() {
     var token = getCookie("token");
     if(!token || token == -1) {
        var msg = "对不起您还没有登陆";
        var url = "../../index.html?url=1";
        showModal(msg);
        doJump(url);
     }
 }
/*----------------------------------------------------------------------------------------------*/
/*-------时间戳的换算-------*/
function timeChange(time){
    function getLocalTime_2(nS) {
        return new Date(parseInt(nS) * 1000);
    }
    var start_time_2 = getLocalTime_2(time);
    var s_date=start_time_2.getDate();
    var s_month=start_time_2.getMonth()+1;
    var s_year=start_time_2.getFullYear();
    var getTime=s_year+'.'+s_month+'.'+s_date
    return getTime;
}

/* -------换算营业时间------ */
function calculateTime(time) {
    var h = parseInt(time/3600);
    h = (h < 10 ? "0" + h : h);
    var m = parseInt((time - h*3600)/60);
    m = (m < 10 ? "0" + m : m);
    return h + ":" + m;
}
/* -------阻止事件冒泡------ */
function stopEventBubble(){
    var e=getEvent();
    if(window.event){
        e.cancelBubble=true;//阻止冒泡
    }else if(e.preventDefault){
        e.stopPropagation();//阻止冒泡
    }
}
function getEvent(){
    if(window.event)    {return window.event;}
    func=getEvent.caller;
    while(func!=null){
        var arg0=func.arguments[0];
        if(arg0){
            if((arg0.constructor==Event || arg0.constructor ==MouseEvent
                || arg0.constructor==KeyboardEvent)
                ||(typeof(arg0)=="object" && arg0.preventDefault
                && arg0.stopPropagation)){
                return arg0;
            }
        }
        func=func.caller;
    }
    return null;
}

$('.back').click(function () {
    history.go(-1);
    $('.back').css({'color':'rgb(0,170,144)'})
});

function LoginModal(locationHref){
    $('#myModal .modal-body').text("您还没有登录，请登录后再操作！");
    $("#myModal .modal-footer button:nth-of-type(1)").text("去登录");
    $("#myModal .modal-footer button:nth-of-type(2)").text("返回");
    $('#myModal').modal();
    $("#myModal .modal-footer button:nth-of-type(1)").click(function(){
        window.location.href = locationHref;
    })
    $("#myModal .modal-footer button:nth-of-type(2)").click(function(){
        $('#myModal').modal("hide");
    })
    $('#myModal').modal();
}

/*获取用户是否赞过店铺*/
function getShopIsUserGiving(shop_id) {
    var token = getCookie("token");
    if(token != -1 && token != undefined){
        var url = "/Shops/getShopIsUserGiving";
        var arg = {};
        arg.shop_id = shop_id;
        ajaxJsonp(url, arg, getGivingResult);
        /* 处理是否赞的结果 */
        function getGivingResult(res) {
            var isGiving = res.data.is_giving;
            if(isGiving==1){
                $(".zan_num").each(function(i,obj){
                    if($(obj).attr("data-id")==shop_id){
                        $(obj).children("div").addClass("heart")
                    }
                })
            }
        }
    }
}
/* 点赞 */
function addShopUserGiving(shop_id,is_cancel) {
    var url = "/Shops/addShopUserGiving";
    var arg = {};
    arg.shop_id = shop_id;
    arg.is_cancel = is_cancel;
    ajaxJsonp(url, arg, null, "post", givingFailed);
}
/* 点赞失败 */
function givingFailed(res) {
    alert("点赞错误");
}
function zan(target,LoginPage) {
    stopEventBubble();
    var token = getCookie("token");
    if(token==null||token==-1||token==undefined){
        LoginPage();
    }else{
        var is_cancel = '';
        var shop_id=$(target).attr("data-id");
        var targetSpan=$(target).children("span");
        var heart_num = parseInt($(target).children("span").text());//店铺的点赞数
        if($(target).children("div").hasClass("heart")) {
            targetSpan.text(" ");
            targetSpan.text(heart_num-1);
            is_cancel = 1;
        } else {
            targetSpan.text(" ");
            targetSpan.text(heart_num+1);
            is_cancel = 0;
        }
        $(target).children("div").toggleClass("heart");
        addShopUserGiving(shop_id,is_cancel);
    }

};
/*解决不同页面跳转问题*/
function indexLinkLogin(){
    var locationHref="webpage/login/login.html?url=1";
    LoginModal(locationHref);
}
function otherLinkLogin(){
    var locationHref="../login/login.html?url=1";
    LoginModal(locationHref);
}
function failMessage(res){
    $('#myModal .modal-body').text(res.status.msg);
    $("#myModal .modal-footer button:nth-of-type(1)").text("返回");
    $("#myModal .modal-footer button:nth-of-type(1)").css({"margin-left":"20%"});
    $("#myModal .modal-footer button:nth-of-type(2)").remove();
    $('#myModal').modal();
}

